# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db.models import signals

class WebComic(models.Model):
    created = models.DateTimeField(_("Creation Date"), auto_now_add=True)
    slug = models.SlugField(primary_key=True, editable=False)# used in the url make up
    title = models.CharField(_("Webcomic Name"),max_length=80, help_text=_("Comic title. Comic book url is generated from this.") )# comic title
    image = models.ImageField(_("Webcomic Head Image"), upload_to="comics/images/%Y/%b/headers/", help_text=_("Defines a header image for the webcomic.") ) 
    thumbnail = models.ImageField(_("Thumbnail"), upload_to="comics/images/%Y/%b/headers/thumbnails/", help_text=_("Little icon used with links. Like a logo!") )
    max_comic_width = models.IntegerField(_("Max Strip Image Width"), default=800, help_text=_("Strips larger then max_comic_width will be resized!"))
    description = models.TextField(_("Description"), blank=True, default=None, null=True)
    owner = models.ForeignKey(User, related_name="comics", verbose_name=_("Webcomic Artist"))
        
    mature_content = models.BooleanField(_("Possible mature content?"), default=False, help_text=_("If this is checked, a mature content warning will be show to the user.") )
    
    def __unicode__(self): return self.title
    
    def link(self): return reverse("comics.webcomic", args=(self.slug,))
    def first_strip(self): return self.strips.order_by('id')[0] # returns first comic strip    
    def last_strip(self): return self.strips.order_by('-id')[0] # returns last comic strip 
    
    get_absolute_url = link # alias
    
    class Meta:
        ordering = ('-created', 'slug')

class Strip(models.Model):
    next = models.ForeignKey('Strip', null=True, default=None, blank=True,
                             related_name="next_comics", verbose_name=_("Next Strip"))
    prev = models.ForeignKey('Strip', null=True, default=None, blank=True, 
                             related_name="prev_comics", verbose_name=_("Previous Strip"))
    
    created = models.DateTimeField(_("Creation Date"), auto_now_add=True)
    webcomic = models.ForeignKey(WebComic, related_name="strips", 
                                 verbose_name=_("Comic Book"))        
    name = models.CharField(_("Strip's name"), max_length=40, 
                            help_text=_("Give a nice title to your comic strip") )
    
    # used to classify comics. Makes search for specific stuff very easy
    label = models.CharField(_("Strip keywords"), max_length=40, 
                             blank=True, null=True, 
                             help_text=_("Use labels to categorize your comic strips. ex: bad boys, vacation, pupils") )
    description = models.TextField(_("Strip description"), 
                                   blank=True, null=True, default=None)
    
    # comic image - mandatory
    image = models.ImageField(_("Strip Image"), 
                              upload_to="comics/images/%Y/%b/comics/", 
                              help_text=_("Strip image showed to the viewer") ) 
    
    enable_comments = models.BooleanField(_('enable comments'))
    registration_required = models.BooleanField(_('registration required'), 
                                                help_text=_("If this is checked, only logged-in users will be able to comment this strip."))
    
    def __unicode__(self):
        return "Strip '%s' from '%s'" % (self.name, self.webcomic.title.capitalize())
    
    def link(self):
        return reverse("comics.strip", args=(self.webcomic.slug, self.id))
        
    get_absolute_url = link # alias
    
    class Meta:
        ordering = ("-created", "-id")
        get_latest_by = "created"

# signals 

# makes sure the new strip has a valid prev link
def strip_update_links_pre(sender, instance, signal, *args, **kwargs):
    # if the strip is being created
    if (instance.prev == instance.next) \
    and (instance.webcomic.strips.count()>0):
        latest = instance.webcomic.strips.latest()
        instance.prev = latest

signals.pre_save.connect(strip_update_links_pre, sender=Strip, dispatch_uid="strip_update_links_pre")

# updating next and prev links
def strip_update_links(sender, instance, signal, *args, **kwargs):
    print "KWARGS :",kwargs
    print "STRIPS COUNT :",instance.webcomic.strips.count()
    
    if kwargs["created"] and (instance.prev != instance.next):
        latest = instance.prev
        latest.next=instance
        latest.save()

signals.post_save.connect(strip_update_links, sender=Strip, dispatch_uid="strip_update_links")

# updates webcomic slug
def webcomic_pre_save(sender, instance, signal, *args, **kwargs):
    from django.template.defaultfilters import slugify
    instance.slug = slugify(instance.title.lower())

# updates webcomic slug
signals.pre_save.connect(webcomic_pre_save, sender=WebComic, dispatch_uid="webcomic_pre_save")